package com.lzh.tiktok.user.interceptor;

import com.lzh.common.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lizhihang
 * @create 2023-01-17 21:39
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LoginUserInterceptor.class);

    /**
     * 需要登录的所有请求都应该先拦截进行验证是否登录
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行无需登录的请求
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();// 匹配器
        boolean match = antPathMatcher.match("/douyin/user/register/**", uri);// 注册
        boolean match1 = antPathMatcher.match("/douyin/user/login/**", uri);// 登录
        boolean match2 = antPathMatcher.match("/douyin/feed", uri);// 视频流
        boolean match3 = antPathMatcher.match("/error", uri);// error
        boolean match4 = antPathMatcher.match("/hello/**", uri);

        //放行无需登录的请求
        if (match || match1 || match2 || match3 || match4) {
            return true;
        }

        // 验证登录状态
        String token = request.getParameter("token");
        //没有抛异常的话就是验签成功
        Long userId = new Long(1);
        try {
            userId = JwtUtils.getUserId(token);
        } catch (Exception e) {
            throw new LoginException("未登录");
        }
        if (userId == null) {
            throw new LoginException("请重新登录后再进行操作");
        }
        return true;
    }
}
